package threadcoreknowledge.stopthreads.scy1;

import java.util.Random;

/**
 * 仔细体会这个案例.
 * 子线程被interrupt后,其线程中isInterrupted返回值为true.子线程可以理会,也可以不理会这次interrupt
 * 当子线程通过sleep方法响应中断后,清除标记位,,isInterrupted返回值为false
 *
 */
public class ThreadMain {
    public static void main(String[] args) throws Exception {

        Runnable runnable = new Runnable() {
            public void run() {


                longTimeMethod(1,1);

                System.out.println("第1次判断isInterrupted:" + Thread.currentThread().isInterrupted());

                longTimeMethod(1,2);

                System.out.println("第2次判断isInterrupted:" + Thread.currentThread().isInterrupted());
                System.out.println("马上要进行sleep了");
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    System.out.println("------进入catch了-------当前线程isInterrupted:"+Thread.currentThread().isInterrupted());
                    e.printStackTrace();
                }

                System.out.println("第3次判断isInterrupted:" + Thread.currentThread().isInterrupted());
                longTimeMethod(1,3);
                System.out.println("第4次判断isInterrupted:" + Thread.currentThread().isInterrupted());
            }

            /**
             *
             * @param multi 基数的倍数
             * @param n 第几次运行该方法
             */
            public void longTimeMethod(int multi,int n) {
                Long _long = 0L;
                Long Max = multi * 59_999_900L;
                long start = System.currentTimeMillis();
                for (long i = 0; i <= Max; i++) {
                    Random random = new Random();
                    int seed = random.nextInt(100);
                    Random random1 = new Random(seed);
                    int seed2 = random1.nextInt(100);
                    Random random2 = new Random(seed2);
                    int i1 = random2.nextInt(100);
                    _long = i1 + _long;
                }

                long end = System.currentTimeMillis();
                System.out.println("第"+n+"次运行,程序耗时:" + (end - start) + "毫秒-----运行结果是:" + _long);
            }
        };

        Thread thread = new Thread(runnable);

        thread.start();
        Thread.sleep(4300);
        thread.interrupt();
        Thread.sleep(5);
        thread.interrupt();
        Thread.sleep(1000*5);
        thread.interrupt();
//        Thread.sleep(1000*2);
//        thread.interrupt();
//        Thread.sleep(1000*2);
//        thread.interrupt();
//        Thread.sleep(1000*2);
//        thread.interrupt();

    }
}
